﻿using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;
using System.Xml.XPath;

namespace Landscape
{
    internal class XsltExtension
    {
        private Hashtable sessionSettings;

        public XsltExtension(Hashtable sessionSettings)
        {
            this.sessionSettings = sessionSettings;
        }

        public string ToLower(string s){
            return s.ToLower();
        }

        public string ToUpper(string s)
        {
            return s.ToUpper();
        }

        public string UCFirst(string s)
        {
            return Globals.UCFirst(s);
        }

        // FIXME: use something like php htmlentities
        public string RemoveHTML(string s) {
            string output = Regex.Replace(s, "<[^>]*>", "");
            return output;
        }

        // returns desired application setting.
        // check for null values also to prevent null values return
        // which is not permitted
        public string AppSetting(string settingName) {
            string settingValue = System.Configuration.ConfigurationManager.AppSettings[settingName];
            return settingValue != null? settingValue: string.Empty;     
        }

        // landscape settings
        public string LibSetting(string settingName)
        {
            string settingValue = Globals.Config.Setting(settingName);
            return settingValue != null ? settingValue : string.Empty;
        }

        // settings valid only for this session
        public string SessionSetting(string settingName) {
            return this.sessionSettings.ContainsKey(settingName) ? this.sessionSettings[settingName] as string : string.Empty;
        }

        public XPathNavigator Split(string s, string sep) {
            string[] seps = { sep};
            string[] values = s.Split(seps, StringSplitOptions.RemoveEmptyEntries);

            XmlDocument docResult = new XmlDocument();
            docResult.AppendChild(docResult.CreateElement("values"));

            if (values.Length > 0) {
                foreach (string value in values) {
                    XmlElement valueElement = docResult.CreateElement("value");
                    valueElement.InnerText = value;
                    docResult.DocumentElement.AppendChild(valueElement);
                }
            }

            return docResult.DocumentElement.CreateNavigator();
        }
    }
}
